package org.budo.cmbc.direct.sdk;

import java.lang.reflect.Method;

import org.budo.support.lang.util.ReflectUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class CMBCDecryptKitDelegate {
    private Object cmbcDecryptKit;

    public CMBCDecryptKitDelegate() {
        if (!ReflectUtil.hasClass("cfca.sm2rsa.common.PKIException")) {
            throw new RuntimeException("please dependency SADK-CMBC-3.1.0.8.jar");
        }

        if (!ReflectUtil.hasClass("cfca.sadk.cmbc.tools.CMBCDecryptKit")) {
            throw new RuntimeException("please dependency CFCADecryptKit-CMBC-3.0.0.2.jar");
        }

        Class targetType = ReflectUtil.classForName("cfca.sadk.cmbc.tools.CMBCDecryptKit");
        this.cmbcDecryptKit = ReflectUtil.newInstance(targetType);
    }

    public void Initialize(String userPrivateFile, String userPrivateFilePassword, String cmbcPublicCertFile) throws Throwable {
        Class targetType = ReflectUtil.classForName("cfca.sadk.cmbc.tools.CMBCDecryptKit");
        Method method = ReflectUtil.getMethod(targetType, "Initialize", new Class[] { String.class, String.class, String.class });
        try {
            ReflectUtil.invokeMethod(this.cmbcDecryptKit, method, new Object[] { userPrivateFile, userPrivateFilePassword, cmbcPublicCertFile });
        } catch (Throwable e) {
            String message = "#36 Initialize CMBCDecryptKit error, userPrivateFile=" + userPrivateFile + ", cmbcPublicCertFile=" + cmbcPublicCertFile + ", error=" + e;
            log.error(message, e);

            throw new RuntimeException(message);
        }
    }

    public String SignAndEncryptMessage(String userPlainBase64Text) throws Throwable {
        Class targetType = ReflectUtil.classForName("cfca.sadk.cmbc.tools.CMBCDecryptKit");
        Method method = ReflectUtil.getMethod(targetType, "SignAndEncryptMessage", new Class[] { String.class });

        return (String) ReflectUtil.invokeMethod(this.cmbcDecryptKit, method, new Object[] { userPlainBase64Text });
    }

    public String DecryptAndVerifyMessage(String envelop) throws Throwable {
        Class targetType = ReflectUtil.classForName("cfca.sadk.cmbc.tools.CMBCDecryptKit");
        Method method = ReflectUtil.getMethod(targetType, "DecryptAndVerifyMessage", new Class[] { String.class });
        return (String) ReflectUtil.invokeMethod(this.cmbcDecryptKit, method, new Object[] { envelop });
    }

    public void Uninitialize() {
        RuntimeException e = new RuntimeException("#55 Uninitialize error");
        log.error("# 56 e=" + e, e);
        throw e;
    }
}